<template>
  <div>
    <div
      class="shebei"
      style="margin-bottom: 1rem"
      v-if="activeTab === 'smart'"
    >
      <el-form ref="smartForm" class="zhineng" :model="form">
        <el-select
          class="zhixiala"
          v-model="form.smartRegion"
          placeholder="智能设备状态"
        >
          <el-option label="完好" :value="1"></el-option>
          <el-option label="待维修" :value="2"></el-option>
        </el-select>
      </el-form>
      <div class="block">
        <el-date-picker
          v-model="smartValue2"
          type="daterange"
          align="right"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
        >
        </el-date-picker>
      </div>
      <el-input
        class="zhixiala"
        v-model="smartInput"
        placeholder="房号"
      ></el-input>
      <el-button
        @click="searchSmart"
        type="primary"
        :loading="smartSearchLoading"
      >
        查询
      </el-button>
    </div>

    <div
      class="shebei"
      style="margin-bottom: 1rem"
      v-if="activeTab === 'family'"
    >
      <el-form ref="familyForm" class="zhineng" :model="form">
        <el-select
          class="zhixiala"
          v-model="form.familyRegion"
          placeholder="家居设备状态"
        >
          <el-option label="完好" :value="1"></el-option>
          <el-option label="待维修" :value="2"></el-option>
        </el-select>
      </el-form>
      <div class="block">
        <el-date-picker
          v-model="familyValue2"
          type="daterange"
          align="right"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
        >
        </el-date-picker>
      </div>
      <el-input
        class="zhixiala"
        v-model="familyInput"
        placeholder="房号"
      ></el-input>
      <el-button
        @click="searchFamily"
        type="primary"
        :loading="familySearchLoading"
      >
        搜索
      </el-button>
    </div>

    <el-tabs
      class="put-con"
      type="border-card"
      v-model="activeTab"
      @tab-click="handleTabChange"
    >
      <el-tab-pane label="智能设备" name="smart">
        <el-table
          :data="smartTableData"
          border
          stripe
          style="width: 100%"
          v-loading="tableLoading"
          element-loading-text="加载中..."
        >
          <el-table-column prop="unitname" label="单位名称"> </el-table-column>
          <el-table-column prop="buildnum" label="幢号"> </el-table-column>
          <el-table-column prop="homenum" label="房号"> </el-table-column>
          <el-table-column prop="homename" label="房主"> </el-table-column>
          <el-table-column prop="airnum" label="空调"> </el-table-column>
          <el-table-column prop="wifiname" label="无线网络"> </el-table-column>
          <el-table-column prop="washnum" label="洗衣机"> </el-table-column>
          <el-table-column prop="createtime" label="授予时间">
            <template slot-scope="scope">
              {{ formatDateTime(scope.row.createtime) }}
            </template>
          </el-table-column>
          <el-table-column prop="smartstatus" label="状态">
            <template slot-scope="scope">
              {{ scope.row.smartstatus === 1 ? "完好" : "待维修" }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-switch
                :active-value="1"
                :inactive-value="2"
                v-model="scope.row.smartstatus"
                @change="handleSmartSwitch(scope.row)"
                :disabled="scope.row.loading"
              >
              </el-switch>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="家居设备" name="family">
        <el-table
          :data="familyTableData"
          border
          stripe
          style="width: 100%"
          v-loading="tableLoading"
          element-loading-text="加载中..."
        >
          <el-table-column prop="unitname" label="单位名称"> </el-table-column>
          <el-table-column prop="buildnum" label="幢号"> </el-table-column>
          <el-table-column prop="homenum" label="房号"> </el-table-column>
          <el-table-column prop="homename" label="房主"> </el-table-column>
          <el-table-column prop="homedesk" label="书桌"> </el-table-column>
          <el-table-column prop="homechair" label="椅子"> </el-table-column>
          <el-table-column prop="homeclothes" label="衣柜"> </el-table-column>
          <el-table-column prop="createtime" label="授予时间">
            <template slot-scope="scope">
              {{ formatDateTime(scope.row.createtime) }}
            </template>
          </el-table-column>
          <el-table-column prop="familystatus" label="状态">
            <template slot-scope="scope">
              {{ scope.row.familystatus === 1 ? "完好" : "待维修" }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-switch
                :active-value="1"
                :inactive-value="2"
                v-model="scope.row.familystatus"
                @change="handleFamilySwitch(scope.row)"
                :disabled="scope.row.loading"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <div class="block fenye">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageNum"
        layout="total, sizes, prev, pager, next, jumper"
        :total="activeTab === 'smart' ? smartTotal : familyTotal"
        background
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeTab: "smart", // 当前激活的标签页（默认智能设备）
      form: {
        smartRegion: "", // 智能设备状态筛选
        familyRegion: "", // 家居设备状态筛选
      },
      // 智能设备筛选变量
      smartValue2: "",
      smartInput: "",
      // 家居设备筛选变量
      familyValue2: "",
      familyInput: "",
      // 日期快捷选项
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },

      smartTableData: [],
      familyTableData: [],

      currPage: 1,
      pageNum: 10,
      smartTotal: 0,
      familyTotal: 0,

      tableLoading: false,
      smartSearchLoading: false,
      familySearchLoading: false,
    };
  },
  created() {
    this.getSmartList();
  },
  methods: {
    handleTabChange() {
      if (this.activeTab === "smart") {
        this.getSmartList();
      } else {
        this.getFamilyList();
      }
    },

    async handleSmartSwitch(row) {
      const originalStatus = row.smartstatus;
      const statusText = row.smartstatus === 1 ? "完好" : "待维修";
      try {
        await this.$confirm(
          `确定更新该智能设备状态为【${statusText}】？`,
          "确认",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            distinguishCancelAndClose: true,
          }
        );

        row.loading = true;
        const res = await this.$axios.post(
          "http://community.byesame.com/house/updatesmartStatus",
          {
            id: row.id,
            smartstatus: row.smartstatus,
            token:
              "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiMjQ1MzMxNzM1N0BxcS5jb20iLCJoZWFkIjoiMjAyNTEwMjUyMTA3NDY1MDUxMTkwLmpwZyIsInR5cGUiOiIxIiwiaWF0IjoxNzYxNTI3ODU2LCJleHAiOjE3NjE2MTQyNTZ9.MLzCheM7nUSUhPR4JtQTr4LHwHOUKP3zoNnO2XwGL0Q",
          }
        );

        this.$message.success(`智能设备状态更新为【${statusText}】`);
        console.log("智能设备更新成功", res);
      } catch (err) {
        if (err.name === "Cancel") {
          row.smartstatus = originalStatus;
          return;
        }
        row.smartstatus = originalStatus;
        this.$message("已取消改变智能状态");
      }
    },

    async handleFamilySwitch(row) {
      const originalStatus = row.familystatus;
      const statusText = row.familystatus === 1 ? "完好" : "待维修";
      try {
        await this.$confirm(
          `确定更新该家居设备状态为【${statusText}】？`,
          "确认",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            distinguishCancelAndClose: true,
          }
        );

        row.loading = true;
        const res = await this.$axios.post(
          "http://community.byesame.com/house/updatefamilyStatus", 
          {
            id: row.id,
            familystatus: row.familystatus,
            token:
              "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiMjQ1MzMxNzM1N0BxcS5jb20iLCJoZWFkIjoiMjAyNTEwMjUyMTA3NDY1MDUxMTkwLmpwZyIsInR5cGUiOiIxIiwiaWF0IjoxNzYxNTI3ODU2LCJleHAiOjE3NjE2MTQyNTZ9.MLzCheM7nUSUhPR4JtQTr4LHwHOUKP3zoNnO2XwGL0Q",
          }
        );

        this.$message.success(`家居设备状态更新为【${statusText}】`);
        console.log("家居设备更新成功", res);
      } catch (err) {
        if (err.name === "Cancel") {
          row.familystatus = originalStatus;
          return;
        }
        row.familystatus = originalStatus;
        this.$message.error("家居设备状态更新失败");
        console.error("家居设备更新失败", err);
      } finally {
        row.loading = false;
      }
    },

    async searchSmart() {
      this.smartSearchLoading = true;
      try {
        const startDate = this.smartValue2?.[0] || "";
        const endDate = this.smartValue2?.[1] || "";
        const res = await this.$axios.get(
          `http://community.byesame.com/house/searchdeviceList?smartstatus=${
            this.form.smartRegion
          }&homenum=${
            this.smartInput
          }&startDate=${startDate}&endDate=${endDate}&currPage=${
            this.currPage - 1
          }&pageNum=${
            this.pageNum
          }&token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiMjQ1MzMxNzM1N0BxcS5jb20iLCJoZWFkIjoiMjAyNTEwMjUyMTA3NDY1MDUxMTkwLmpwZyIsInR5cGUiOiIxIiwiaWF0IjoxNzYxNTI3ODU2LCJleHAiOjE3NjE2MTQyNTZ9.MLzCheM7nUSUhPR4JtQTr4LHwHOUKP3zoNnO2XwGL0Q`
        );

        this.smartTableData = (res.data.data || []).map((item) => ({
          ...item,
          loading: false,
        }));
        this.smartTotal = res.data.total || 0;
        if (
          !this.form.smartRegion &&
          !this.smartInput &&
          !startDate &&
          !endDate
        ) {
          this.getSmartList();
        }
      } catch (err) {
        this.$message.error("智能设备查询失败");
        console.error("智能查询错误", err);
      } finally {
        this.smartSearchLoading = false;
      }
    },

    async searchFamily() {
      this.familySearchLoading = true;
      try {
        const startDate = this.familyValue2?.[0] || "";
        const endDate = this.familyValue2?.[1] || "";
        const res = await this.$axios.get(
          `http://community.byesame.com/house/searchdeviceList?familystatus=${
            this.form.familyRegion
          }&homenum=${
            this.familyInput
          }&startDate=${startDate}&endDate={endDate}&currPage=${
            this.currPage - 1
          }&pageNum=${this.pageNum}&token=
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiMjQ1MzMxNzM1N0BxcS5jb20iLCJoZWFkIjoiMjAyNTEwMjUyMTA3NDY1MDUxMTkwLmpwZyIsInR5cGUiOiIxIiwiaWF0IjoxNzYxNTI3ODU2LCJleHAiOjE3NjE2MTQyNTZ9.MLzCheM7nUSUhPR4JtQTr4LHwHOUKP3zoNnO2XwGL0Q`
        );
        this.familyTableData = (res.data.data || []).map((item) => ({
          ...item,
          loading: false,
        }));
        this.familyTotal = res.data.total || 0;

        if (
          !this.form.familyRegion &&
          !this.familyInput &&
          !startDate &&
          !endDate
        ) {
          this.getFamilyList();
        }
      } catch (err) {
        this.$message.error("家居设备搜索失败");
        console.error("家居搜索错误", err);
      } finally {
        this.familySearchLoading = false;
      }
    },

    handleSizeChange(val) {
      this.pageNum = val;
      this.currPage = 1;
      if (this.activeTab === "smart") {
        this.getSmartList();
      } else {
        this.getFamilyList();
      }
    },

    handleCurrentChange(val) {
      this.currPage = val;
      if (this.activeTab === "smart") {
        this.getSmartList();
      } else {
        this.getFamilyList();
      }
    },

    formatDateTime(utcTime) {
      if (!utcTime) return "";
      const date = new Date(utcTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    async getSmartList() {
      this.tableLoading = true;
      try {
        const res = await this.$axios.get(
          `http://community.byesame.com/house/searchdeviceList?smartstatus=&familystatus=&homenum=&startDate=&endDate=&currPage=${
            this.currPage - 1
          }&pageNum=${
            this.pageNum
          }&token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiMjQ1MzMxNzM1N0BxcS5jb20iLCJoZWFkIjoiMjAyNTEwMjUyMTA3NDY1MDUxMTkwLmpwZyIsInR5cGUiOiIxIiwiaWF0IjoxNzYxNTI3ODU2LCJleHAiOjE3NjE2MTQyNTZ9.MLzCheM7nUSUhPR4JtQTr4LHwHOUKP3zoNnO2XwGL0Q`
        );
        this.smartTableData = (res.data.data || []).map((item) => ({
          ...item,
          loading: false,
        }));
        this.smartTotal = res.data.total || 0;
      } catch (err) {
        this.$message.error("智能设备数据加载失败");
        console.error("智能加载错误", err);
      } finally {
        this.tableLoading = false;
      }
    },

    async getFamilyList() {
      this.tableLoading = true;
      try {
        const res = await this.$axios.get(
          `http://community.byesame.com/house/searchdeviceList?smartstatus=&familystatus=&homenum=&startDate=&endDate=&currPage=${
            this.currPage - 1
          }&pageNum=${
            this.pageNum
          }&token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiMjQ1MzMxNzM1N0BxcS5jb20iLCJoZWFkIjoiMjAyNTEwMjUyMTA3NDY1MDUxMTkwLmpwZyIsInR5cGUiOiIxIiwiaWF0IjoxNzYxNTI3ODU2LCJleHAiOjE3NjE2MTQyNTZ9.MLzCheM7nUSUhPR4JtQTr4LHwHOUKP3zoNnO2XwGL0Q`
        );
        this.familyTableData = (res.data.data || []).map((item) => ({
          ...item,
          loading: false,
        }));
        this.familyTotal = res.data.total || 0;
      } catch (err) {
        this.$message.error("家居设备数据加载失败");
        console.error("家居加载错误", err);
      } finally {
        this.tableLoading = false;
      }
    },
  },
};
</script>

<style scoped>
.shebei {
  display: flex;
  gap: 1rem;
  align-items: center;
  flex-wrap: wrap;
}

.zhineng {
  width: 22.25rem;
}

.el-select {
  display: block;
  width: 100%;
}

.zhixiala {
  width: 22.25rem;
}

.put-con {
  margin-top: 1.875rem;
}

.el-button--small,
.el-button--small.is-round {
  padding: 0.5625rem 2.5rem;
}

.fenye {
  float: right;
  margin: 1.875rem 1.25rem;
}

::v-deep .el-date-editor--daterange.el-input {
  width: 22.25rem !important;
}

::v-deep .el-table__empty-text,
::v-deep .el-loading-mask {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>